<?php

namespace App\Console\Commands;

use App\Enum\MonitorEnum;
use App\Enum\OrderEnum;
use App\Enum\ThirdImportEnum;
use App\Enum\ThirdOrderEnum;
use App\Models\ThirdImportBatchModel;
use App\Models\ThirdImportDetailModel;
use App\Models\ThirdOrderAllModel;
use App\Services\MapService;
use App\Services\MonitorService;
use App\Services\OrderService;
use App\Services\Tools\HelpService;
use App\Services\VehicleConfigService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class OrderChangedFeedbackCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:changed-feedback';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单变更，同步信息到三方订单总表。';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        $redis = app('redis.connection');

        while(1) {
            $second = date('s');

            if ($second >= 57) {
                $this->info("second = $second, wait for next time.");
                break;
            } else  $this->info("second = $second, keep going.");
            $orderId = $redis->lpop(ThirdOrderEnum::R_ORDER_CHANGE_FEEDBACK_KEY);
            try {
                if (!empty($orderId)) {
                    // 将订单信息回馈到三方订单总表
                    OrderService::orderChangeFeedback($orderId);
                    // 删除所有此订单ID的处理
                    $redis->lrem(ThirdOrderEnum::R_ORDER_CHANGE_FEEDBACK_KEY, 0,$orderId);
                }
            }catch (Exception $e){
                // 再将orderId加入 到队列末尾
                OrderService::addOrderChanged($orderId);
                MonitorService::addException(MonitorEnum::MONITOR_TYPE_ORDER_FEEDBACK,sprintf("订单ID（%d）：E=%s", $orderId, $e->getMessage()));
            }
            usleep(10000);
        }
        return 0;
    }
}
